package com.ccg.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Email {
    private  static Properties props = new Properties();
    private static final String MY163EMAIL = "13242268114@163.com";
    private static final String PASSWORD = "abc5499";

    static {
        props.setProperty("mail.smtp.host", "smtp.163.com");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        //邮箱发送服务器端口,这里设置为465端口
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
    }

    public static void sendEmil(String toEmail,String code) throws MessagingException {
        //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY163EMAIL, PASSWORD);
            }
        });
        //通过会话,得到一个邮件,用于发送
        Message msg = new MimeMessage(session);
        //设置发件人
        msg.setFrom(new InternetAddress(MY163EMAIL));
        //设置收件人,to为收件人,cc为抄送,bcc为密送
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(toEmail, false));
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(toEmail, false));
        //设置邮件消息
        msg.setSubject("瑞豪酒店");
        msg.setContent("验证码： "+code,"text/html;charset=utf-8");
        //调用Transport的send方法去发送邮件
        Transport.send(msg);
    }
    //生成验证码
    public static String getEmailCode(){
        Random r = new Random();
        return ""+r.nextInt(10)+r.nextInt(10)+r.nextInt(10)+r.nextInt(10);
    }
    //判断邮箱地址是否有效
    public static boolean isEmailAddress(String toEmail) {
        boolean isExist = false;

        Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");
        Matcher m = p.matcher(toEmail);
        boolean b = m.matches();
        if (b) {
            System.out.println("有效邮件地址");
            isExist = true;
        } else {
            System.out.println("无效邮件地址");
        }
        return isExist;
    }

}
